<template>
  <div class="wrap">
    <div class="header">
      <div>新增订单</div>
      <div class="headerContent">
        <el-form ref="form" :model="memberForm" label-width="80px">
          <el-row>
            <el-col :span="5">
              <el-form-item label="会员：">
                <el-select v-model="memberForm.member" placeholder="请选择会员名称">
                  <el-option v-for="item in memberOptions" :key="item.userId" :value="item.userId" :label="item.surName+item.userName" />
                </el-select>

              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-button  @click="selectUser ()">选择用户</el-button>
            </el-col>
            <el-col :span="3" style="text-align:right;">
              <el-button @click="userbtn">确认</el-button>
            </el-col>
          </el-row>
        </el-form>
        <div class="addressBox">
          <div v-if="addresslist.length != 0" class="address_content">
            <div v-for="(item,index) in addresslist" :key="index" class="address_con_item" @click="addre(index)">
              <img v-if="item.isDefault == true" src="@/assets/address1.png" alt="" class="address_img">
              <img v-if="item.isDefault == false" src="@/assets/address.png" alt="" class="address_img">
              <div class="address_con">
                <div class="address_name">
                  <div>{{ item.name }}</div>
                  <div>{{ item.tel }}</div>
                </div>
                <div class="address_pro">
                  <div>{{ item.province }}</div>
                  <div>{{ item.city }}</div>
                  <div>{{ item.county }}</div>
                </div>
                <div class="address_detail">{{ item.addressDetail }}</div>
                <div v-if="item.isDefault == true" class="address_other">
                  默认地址
                </div>
              </div>
            </div>
          </div>
          <div v-if="addresslist.length == 0" class="address_content nohaveshop">
            <p class="p1">地址信息为空~~</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="dataTable">
      <el-card class="filter-container" shadow="never">
        <div>
          <i class="el-icon-tickets" />
          <span>数据列表</span>
          <el-button style="float:right;margin-right: 15px" size="small" @click="selectGoods()">选择商品</el-button>
        </div>
      </el-card>
      <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row style="margin-top:10px" @selection-change="handleSelectionChange">
<!--        <el-table-column type="selection" width="60" align="center" />-->

        <el-table-column align="center" label="商品ID" prop="goodsId" />

        <el-table-column align="center" label="名称" prop="goodsName" />

        <el-table-column align="center" label="价格">
          <template slot-scope="scope">
            <div>{{ scope.row.retailPrice }}</div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="货号">
          <template slot-scope="scope">
            <div>{{ scope.row.goodsSn }}</div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="图片">
          <template slot-scope="scope">
            <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40">
          </template>
        </el-table-column>

        <el-table-column align="center" label="详情">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>

        <el-table-column align="center" label="数量" prop="num" width="200px">
          <template slot-scope="scope">
            <el-input-number size="mini" :min="1" :value="scope.row.num" @input="handleBlur" @change="handleChange( scope.row )" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="resultBox">
        <div>
          <div>pv：</div>
          <div>{{ pvValue }}</div>
        </div>
        <div>
          <div>合计：</div>
          <div><span>${{ totalPrice }}</span></div>
        </div>
        <div>
          <div>运费：</div>
          <div class="inputbox"><el-input v-model="freight" style="display:inline-block;width:100px;margin-right:10px" />港元</div>
        </div>
        <div>
          <div>折扣：</div>
          <div class="inputbox"><el-input v-model="discount" style="display:inline-block;width:100px;margin-right:10px" />折</div>
        </div>
        <div>
          <el-button @click="jisuanAll">确认</el-button>
        </div>
        <div>
          <div>总金额：</div>
          <div><span>${{ totalAmount }}</span></div>
        </div>

      </div>
    </div>

    <!-- 订单状态表单 -->
    <div>
      <el-form ref="userFrom" :model="orderData" label-width="150px">
        <el-form-item label="订单状态：" prop="stauts">
          <el-select v-model="orderData.status" placeholder="全部">
            <el-option  key="100" :value="100" label="已完成" />
            <el-option  key="101" :value="101" label="待付款" />
            <el-option  key="102" :value="102" label="已取消" />
            <el-option  key="103" :value="103" label="已取消系统" />
<!--            <el-option  key="201" :value="201" label="已支付" />-->
            <el-option  key="205" :value="205" label="待发货" />
            <el-option  key="401" :value="401" label="待收货" />
            <el-option  key="402" :value="402" label="待评价" />
            <el-option  key="501" :value="501" label="已退款" />
            <el-option  key="502" :value="502" label="退款中" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式：" prop="pay">
          <el-select v-model="orderData.pay" placeholder="全部">
            <el-option key="4" :value="4" label="现金" />
            <el-option key="5" :value="5" label="八達通" />
            <el-option key="6" :value="6" label="VISA" />
            <el-option key="7" :value="7" label="Master" />
            <el-option key="8" :value="8" label="銀聯" />
            <el-option key="9" :value="9" label="EPS" />
            <el-option key="2" :value="2" label="FirstPay" />
             <el-option key="1" :value="1"  label="PayPal" />
             <el-option key="3" :value="3" label="ATM支付" />
            <el-option key="10" :value="10" label="支付寶 (Alipay)" />
            <el-option key="11" :value="11" label="微信支付(WeChat Pay)" />
            <el-option key="12" :value="12" label="其他（請備註）" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="addressDetail">
          <el-input v-model="orderData.addressDetail" type="textarea" :rows="4" placeholder="请输入详细地址" style="width:300px" />
        </el-form-item>
      </el-form>
    </div>

    <!-- 按钮 -->
    <div style="text-align:center">
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button>取消</el-button>
    </div>

    <el-dialog :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="dialogForm" label-width="100px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="搜索商品：">
            </el-form-item>
          </el-col>
          <el-col :span="6">
              <el-input v-model="dialogForm.searchinput" placeholder="请输入商品名称" />
          </el-col>
          <el-col :span="6">
              <el-input v-model="dialogForm.goodsSn" placeholder="请输入商品编号" />
          </el-col>
          <el-col :span="6">
              <el-cascader
                v-model="dialogForm.categoryId"
                clearable
                placeholder="请选择分类名称"
                expand-trigger="hover"
                :props="{ checkStrictly: true }"
                :options="goodsCategoryOptions"
              />
          </el-col>
          <el-col :span="2" style="text-align:right;">
            <el-button @click="searchbtn">搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table v-loading="Loading" ref="singleTable" :data="dialoglist" element-loading-text="正在查询中。。。" border fit highlight-current-row style="margin-top:10px" @selection-change="handleSelection">
        <el-table-column type="selection" width="60" align="center" />

        <el-table-column align="center" label="商品ID" prop="goodsId" />

        <el-table-column align="center" label="名称" prop="goodsName" />

        <el-table-column align="center" label="价格">
          <template slot-scope="scope">
            <div>{{ scope.row.retailPrice }}</div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="货号">
          <template slot-scope="scope">
            <div>{{ scope.row.goodsSn }}</div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="图片">
          <template slot-scope="scope">
            <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40">
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="Loadpage"
        layout="prev, pager, next, jumper"
        :total="LoadTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="sureBtn">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogUserFormVisible">
      <el-form ref="form" :model="dialogUserForm" label-width="100px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="搜索用户：">
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-input v-model="dialogUserForm.userName" placeholder="请输入用户名称" />
          </el-col>
          <el-col :span="6">
            <el-input v-model="dialogUserForm.mobile" placeholder="请输入用户手机" />
          </el-col>
          <el-col :span="6">
            <el-input v-model="dialogUserForm.inviteCode" placeholder="请输入用户账号" />
          </el-col>
          <el-col :span="2" style="text-align:right;">
            <el-button @click="searchbtnUser">搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table v-loading="Loading" :data="memberOptions" element-loading-text="正在查询中。。。" border fit highlight-current-row style="margin-top:10px" >
<!--        <el-table-column type="selection" width="60" align="center" />-->
        <el-table-column label="用户ID" width="100" align="left">
          <template scope="scope">
            <el-radio :label="scope.row.userId"  v-model="UserRadio" @change.native="getCurrentRow(scope.row.userId)"></el-radio>
          </template>
        </el-table-column>
<!--        <el-table-column align="center" label="商品ID" prop="userId" />-->

        <el-table-column align="center" label="姓" prop="surName" />
        <el-table-column align="center" label="名" prop="userName" />
      </el-table>
      <el-pagination
        :current-page.sync="LoadUserpage"
        layout="prev, pager, next, jumper"
        :total="LoadUserTotal"
        @size-change="handleUserSizeChange"
        @current-change="handleUserCurrentChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserFormVisible = false">取消</el-button>
        <el-button type="primary" @click="sureuserBtn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import {
  getUser,
  getGoods,
  getAddress,
  pay,
  innsert
} from '@/api/order'
import { listCategory } from '@/api/category'
export default {
  name: 'OrderOV',
  data() {
    return {
      memberForm: {
        member: ''
      }, // 地址会员搜索表单
      memberOptions: [
      ], // 会员选择下拉框赋值
      addresslist: [],
      listLoading: false,
      dialogForm: {
        searchinput: '',
        goodsSn: '',
        categoryId: ''
      },
      dialogUserForm:{
        userName: '',
        mobile: '',
        inviteCode: ''
      },
      LoadUserpage:1,
      LoadUserTotal:null,//用户查询总数
      UserRadio:null,//用户单选
      LoadUserlimit:10,
      Loading: false,
      Loadlimit: 10,
      Loadpage: 1,
      LoadTotal: null,
      dialoglist: [],
      dialogSelection: [],
      list: [],
      multipleSelection: [],
      input_number_value: 1,
      dialogFormVisible: false,
      dialogUserFormVisible: false,
      goodsCategoryOptions: [],
      pvValue: 0,
      totalPrice: 0,
      freight: 0,
      addid: '',
      discount: 0,
      totalAmount: 0,
      orderData: {

      },
      selectArray:[]
    }
  },
  mounted() {
    this.gethuiyuan()

  },
  methods: {
    addre(e) {
      for (var i = 0; i < this.addresslist.length; i++) {
        this.addresslist[i].isDefault = false
      }
      this.addresslist[e].isDefault = true
      this.addid = this.addresslist[e].addressId
    },
    searchbtnUser() {

      this.gethuiyuan(this.dialogUserForm.userName, this.dialogUserForm.mobile, this.dialogUserForm.inviteCode)
    },
    gethuiyuan(userName,mobile,inviteCode) {
      getUser({ limit: this.LoadUserlimit, page: this.LoadUserpage, userName: userName, mobile: mobile, inviteCode: inviteCode }).then(response => {
        if (response.data.errno == 0) {
          this.memberOptions = response.data.data.list
          this.LoadUserTotal = response.data.data.total
        } else {
          this.memberOptions = []
        }
      })
    },
    userbtn() {
      getAddress(this.memberForm.member).then(response => {
        if (response.data.errno == 0) {
          this.addresslist = response.data.data
          for (var i = 0; i < this.addresslist.length; i++) {
            if (this.addresslist[i].isDefault == true) {
              this.addid = this.addresslist[i].addressId
            }
          }
        } else {
          this.addresslist = []
        }
      })
    },
    // 搜索商品展示
    searchbtn() {
      var id;
      if(this.dialogForm.categoryId.length != 0){
        id = this.dialogForm.categoryId[this.dialogForm.categoryId.length-1]
      }
      console.log(id)
      this.searchdialogdata(this.dialogForm.searchinput,this.dialogForm.goodsSn,id)
    },
    // 打开弹框搜索数据
    searchdialogdata(e, goodsSn, categoryId) {
      getGoods({ limit: this.Loadlimit, page: this.Loadpage, goodsName: e, goodsSn: goodsSn, categoryId: categoryId }).then(response => {
        if (response.data.errno == 0) {
          this.dialoglist = response.data.data.list
          this.LoadTotal = response.data.data.total
          this.getselect()
        } else {
          this.dialoglist = []
          this.LoadTotal = null
        }
      })
    },
    selectGoods() {
      this.dialogFormVisible = true
      this.searchdialogdata()
      this.getCategoryList()
    },
    selectUser() {
      this.dialogUserFormVisible = true
      this.gethuiyuan()
    },
    getCurrentRow(index){
      // this.UserRadio = index
      console.log(this.UserRadio)
    },
    //用户确定按钮
    sureuserBtn(){
      this.memberForm.member = this.UserRadio
      this.dialogUserFormVisible = false
    },
    getselect(){
      var array = JSON.parse(localStorage.getItem('selectgoodid'))
      if(array){
        this.$nextTick(()=>{
          this.dialoglist.forEach(row=>{
            if(array.indexOf(row.goodsId)>=0){
              this.$refs.singleTable.toggleRowSelection(row,true);
            }
          })
        })
      }
    },
    getCategoryList() {
      listCategory().then((response) => {
        this.goodsCategoryOptions = response.data.data.categoryList
      })
    },
    getGoodsCategoryByIds(ids) {
      let name
      let parentName
      let pParentName
      let ret = 0
      for (let i = 0; i < this.goodsCategoryOptions.length; i++) {
        if (this.goodsCategoryOptions[i].value === ids[0]) {
          parentName = this.goodsCategoryOptions[i].label
          ret = 0
          for (let j = 0; j < this.goodsCategoryOptions[i].children.length; j++) {
            if (this.goodsCategoryOptions[i].children[j].value === ids[1]) {
              ret = 1
              name = this.goodsCategoryOptions[i].children[j].label
              for (let k = 0; k < this.goodsCategoryOptions[i].children[j].children.length; k++) {
                if (this.goodsCategoryOptions[i].children[j].children[k].value === ids[2]) {
                  ret = 2
                  pParentName = this.goodsCategoryOptions[i].children[j].children[k].label
                }
              }
            }
          }
        }
      }
      return {
        goodsCategoryId: ids[ret],
        parentCategoryName: parentName,
        goodsCategoryName: name,
        pParentCategoryName: pParentName
      }
    },
    handleSizeChange(val) {
      this.Loadlimit = val
      this.searchdialogdata(this.dialogForm.searchinput,this.dialogForm.goodsSn)
      // console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.Loadpage = val
      this.searchdialogdata(this.dialogForm.searchinput,this.dialogForm.goodsSn)
      // console.log(`当前页: ${val}`)
    },
    handleUserSizeChange(val) {
      this.LoadUserlimit = val
      this.gethuiyuan(this.dialogUserForm.userName, this.dialogUserForm.mobile, this.dialogUserForm.inviteCode)
      console.log(`每页 ${val} 条`)
    },
    handleUserCurrentChange(val) {
      this.LoadUserpage = val
      this.gethuiyuan(this.dialogUserForm.userName, this.dialogUserForm.mobile, this.dialogUserForm.inviteCode)
      console.log(`当前页: ${val}`)
    },
    // 弹框里面的多选
    handleSelection(val) {
      this.dialogSelection = val
      var array = []
      if(this.dialogSelection.length!=0){
        for(var i=0;i<this.dialogSelection.length;i++){
          array.push(this.dialogSelection[i].goodsId)
        }
      }
      this.selectArray = array
      localStorage.setItem('selectgoodid',JSON.stringify(this.selectArray))
    },
    // 弹框确认按钮
    sureBtn() {
      if (this.dialogSelection.length == 0) {
        this.$message({
          type: 'error',
          message: '请选择商品'
        })
      } else {
        this.dialogFormVisible = false
        this.listLoading = true
        this.gettabledata()
      }
    },
    // 根据弹框里面选择的数据进行筛选
    gettabledata() {
      this.listLoading = false
      this.list = this.dialogSelection
    },
    // 多选按钮选择的内容
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.totalPriceAll()
    },
    // table的数量变化
    handleBlur(value) {
      this.input_number_value = value
    },
    handleChange(data) {
      data.num = this.input_number_value
      // data.totalNum = (data.litemallGoods.counterPrice*data.num).toFixed(2)
      // // this.numChange1( data );
      // this.totalPricess()
      // this.totalNumss()
      // this.totalPriceYing()
      console.log(data)
    },

    // 查看详情
    handleDetail(row) {

    },
    // 删除操作
    handleDelete(row) {

    },
    // 合计pv等数值变化
    totalPriceAll() {
      var total = 0
      this.multipleSelection.forEach(item => {
        total += Number(item.retailPrice)
      })
      this.totalPrice = total.toFixed(2)
      // this.pvValue = total.toFixed(2)
      // this.totalAmount = total.toFixed(2)
    },
    jisuanAll() {
      if (this.list.length == 0) {
        this.$message({
          type: 'error',
          message: '暂时没有选择商品'
        })
      } else {
        var arr = []
        for (var i = 0; i < this.list.length; i++) {
          arr.push(this.list[i])
        }
        console.log(arr)
        pay({ list: arr, discount: this.discount, freightPrice: this.freight }).then(response => {
          console.log(response)
          if (response.data.errno == 0) {
            this.$message({
              type: 'success',
              message: '成功'
            })
            this.pvValue = response.data.data.pv
            this.totalPrice = response.data.data.goodsPrice
            console.log(this.totalPrice)
            this.freight = response.data.data.freightPrice
            this.discount = response.data.data.discount
            this.totalAmount = response.data.data.orderPrice
            console.log(this.totalAmount)
          }
        })
      }
    },
    onSubmit() {
      var arr = []
      if (this.list.length == 0) {
        this.$message({
          type: 'error',
          message: '暂时没有选择商品'
        })
      } else {

        for (var i = 0; i < this.list.length; i++) {
          arr.push(this.list[i])
        }
      }
      innsert({ list: arr, addressId: this.addid, userId: this.memberForm.member, goodsPrice: this.totalPric, discount: this.discount, freightPrice: this.freight, orderPrice: this.totalAmount, orderStatus: this.orderData.status, remarks: this.orderData.addressDetail, payType: this.orderData.pay }).then(response => {
        console.log(response)
        this.multipleSelection = []
        this.memberForm = {
          member: ''
        },
        this.memberOptions = [] // 会员选择下拉框赋值
        this.addresslist = []
        this.listLoading = false,
        this.dialogForm = {
          searchinput: ''
        },
        this.Loading = false,
        this.Loadlimit = 10,
        this.Loadpage = 1,
        this.LoadTotal = null,
        this.dialoglist = [],
        this.dialogSelection = [],
        this.list = [],
        this.multipleSelection = [],
        this.input_number_value = 1,
        this.dialogFormVisible = false,
        this.pvValue = 0,
        this.totalPrice = 0,
        this.freight = 0,
        this.addid = '',
        this.discount = 0,
        this.totalAmount = 0,
        this.orderData = {

        }
      })
    }
  }
}
</script>
<style scoped>
  .wrap{
    width: 100%;
    box-sizing: border-box;
    background: white;
    padding-bottom: 100px;
  }
  .header{
    width: 100%;
    box-sizing: border-box;
    padding: 5px;
    background: white;
    padding-bottom: 10px;
    border-bottom: 2px solid rgb(222,222,222);
  }
  .header>div:nth-child(1){
    font-weight: bolder;
    font-size: 18px;
  }
  .headerContent{
    margin: 10px 0px;
  }
  .addressBox{
    width: 100%;
    box-sizing: border-box;
    padding: 0px 30px;
  }
  .address_content{
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    box-sizing: border-box;
  }
  .address_con_item{
    width: 23.5%;
    box-sizing: border-box;
    height: 200px;
    position: relative;
    margin-bottom: 15px;
    margin-right: 2%;
  }
  .address_con_item:nth-child(4n){
    margin-right: 0%;
  }
  .address_img{
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    /* width: 262px; */
    /* height: 200px; */
  }
  .address_con{
    width: 100%;
    box-sizing: border-box;
    position: absolute;
    top: 20px;
    padding: 0px 15px;
  }
  .address_name{
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #D9D9D9;
    font-size: 15px;
    line-height: 30px;
    padding-bottom: 5px;
    margin-bottom: 5px;
  }
  .address_name>div:nth-child(1){
    line-height: 30px;
  }
  .address_pro{
    display: flex;
    align-items: center;
    line-height: 25px;
    font-size: 15px;
  }
  .address_pro>div{
    margin-right: 10px;
  }
  .address_detail{
    word-break: break-word;
    font-size: 15px;
    color: #999999;
    line-height: 25px;
    height: 70px;
  }
  .address_other{
    font-size: 16px;
    font-weight: bolder;
  }
  .nohaveshop{
    width: 100%;
    text-align: center;
  }
  .nohaveshop p {
    font-size: 22px;
    color: #999;
    text-align: center;
  }
  .dataTable{
    margin: 0px 5px;
    box-sizing: border-box;
    margin-top: 10px;
  }
  .dataTable span{
    line-height: 32px;
  }
  .resultBox{
    width: 100%;
    text-align: right;
  }
  .resultBox>div{
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin: 10px 0px;
    font-size: 16px;
  }
  .resultBox>div:nth-child(1){
    font-weight: bolder;
  }
  .resultBox>div span{
    color: tomato;
  }
  .inputbox{
    width: 150px;
    text-align: left;
  }
</style>
